package com.cheetah.start.common.filter;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import cn.hutool.core.util.StrUtil;
import org.slf4j.MDC;

/**
 * @author Feel
 * @date 2021/11/13 15:42
 * @Description:
 */
public class RetainSqlFilter extends Filter<ILoggingEvent> {
    /**
     * 记录 sql 的 增删改 debug日志
     *
     * @param event 事件
     * @return {@link FilterReply}
     */
    @Override
    public FilterReply decide(ILoggingEvent event) {
        // 正则一直尝试失败
        // String pattern = "\\*(drop|delete|update|insert).*$";
        String format = event.getFormattedMessage().toLowerCase();
        boolean insert = format.contains("insert");
        boolean into = format.contains("into");
        boolean update = format.contains("update");
        boolean set = format.contains("set");
        boolean delete = format.contains("delete");
        boolean from = format.contains("from");
        String loggerName = event.getLoggerName();
        String haveLogName = MDC.get("logname");
        if (StrUtil.isNotBlank(haveLogName)){
            String[] split = haveLogName.split(",");
            for (String s : split) {
                if (loggerName.equals(s)){
                    return FilterReply.ACCEPT;
                }
            }
        }
        if ((insert && into) || (update && set) || (delete && from)) {
            if (StrUtil.isBlank(haveLogName)) {
                MDC.put("logname", loggerName);
            } else {
                String s = haveLogName + "," + loggerName;
                MDC.put("logname", s);
            }
            return FilterReply.ACCEPT;
        }
        return FilterReply.DENY;
    }
}
